<link rel="stylesheet" th:href="@{admin/plugins/treegrid/jquery.treegrid.css}">

<div class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1 class="m-0 text-dark">权限管理</h1>
            </div><!-- /.col -->
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a th:href="@{admin}">首页</a></li>
                    <li class="breadcrumb-item active">文章管理</li>
                    <li class="breadcrumb-item active">权限管理</li>
                </ol>
            </div><!-- /.col -->
        </div><!-- /.row -->
    </div><!-- /.container-fluid -->
</div>
<!-- Main content -->
<section class="content">
    <div class="card card-body">
        <div id="toolbar">
            <shiro:hasPermission name="permission:add">
                <button id="btn_add" type="button" class="btn btn-primary">
                    <span class="fas fa-plus" aria-hidden="true"></span>新增
                </button>
            </shiro:hasPermission>
        </div>
        <table id="menuTable" class="mt-2" data-mobile-responsive="true" data-click-to-select="true"></table>
    </div>

</section>

<!-- 表单模态框 -->
<div class="modal fade" id="formModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="formTitle"></h5>
                <button type="button" class="close" data-dismiss="modal">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div id="formContent"></div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="saveOrUpdateBtn" onclick="saveOrUpdate()">保存
                </button>
            </div>
        </div>
    </div>
</div>

<div id="permissionLayer" style="display: none;padding: 20px;">
    <ul id="permissionTree" class="ztree"></ul>
</div>

<script th:src="@{admin/plugins/treegrid/jquery.treegrid.min.js}"></script>
<script th:src="@{admin/plugins/treegrid/jquery.treegrid.extension.js}"></script>
<script th:src="@{admin/plugins/treegrid/tree.table.js}"></script>
<script>

    var editFlag = Core.parseBool("[[${@perms.hasPerm('permission:edit')}]]");
    var deleteFlag = Core.parseBool("[[${@perms.hasPerm('permission:delete')}]]");

    var menuType = "1";/*默认选中菜单类型*/
    var menuCheckedType = 0;/*选中的上级的菜单类型*/
    var detailMenuCheckedType;/*详情中选中的上级的菜单类型*/

    var treeTableConf = {
        id: "menuTable",
        table: null,
        columns: [
            {
                field: 'selectItem',
                radio: true
            },
            {
                title: '菜单名称',
                field: 'name',
                align: 'center',
            },
            {
                title: '菜单URL',
                field: 'url',
                align: 'center',
            },
            {
                title: '权限标识',
                field: 'perms',
                align: 'center',
            },
            {
                title: '类型',
                field: 'type',
                align: 'center',
                width: '60px',
                formatter: function (row, index) {
                    switch (row.type) {
                        case 0 :
                            return '<span class="badge badge-primary">目录</span>';
                        case 1 :
                            return '<span class="badge badge-secondary">菜单</span>';
                        case 2 :
                            return '<span class="badge badge-info">按钮</span>';
                    }
                }
            },
            {
                title: '图标',
                field: 'icon',
                align: 'center',
                width: '60px',
                formatter: function (row, index) {
                    if (row.type !== 2) {
                        return '<i class="' + row.icon + ' fa-lg"></i>';
                    } else {
                        return "";
                    }
                }
            },
            {
                title: '排序',
                field: 'orderNum',
                align: 'center',
                width: '60px'
            },
            {
                title: '权限描述',
                field: 'description',
                align: 'center',
            },
            {
                field: 'operation',
                title: '操作',
                align: "center",
                width: '150px',
                formatter: function (row, index) {
                    var edit = editFlag && row.status === 1 ? '<button class="btn btn-info btn-sm btn_edit" onclick="editRow(' + row.permissionId + ')">编辑</button>' : '';
                    var del = deleteFlag ? '<button class="btn btn-danger btn-sm ml-1 btn_del" onclick="deleteRow(' + row.permissionId + ')">删除</button>' : '';
                    return edit + del;
                }
            }
        ]
    }

    $(function () {
        var table = new TreeTable(treeTableConf.id, "/permission/list", treeTableConf.columns, "permissionId");
        table.setExpandColumn(1);
        table.setIdField("permissionId");
        table.setCodeField("id");
        table.setParentCodeField("parentId");
        /*table.setExpandAll(true);*/
        table.setStriped(false);
        table.init();
        treeTableConf.table = table;
    })

    // 新增
    $('#btn_add').on('click', function () {
        Core.load("#formContent", "/permission/add", function () {
            $('#formTitle').text('新增')
            $("#formModal").modal('show');
        });
    })


    function saveOrUpdate() {
        var $f = $('#permissionForm');
        var valid = $f[0].checkValidity();
        var url = $f.find("input[name='permissionId']").val() ? "/permission/edit" : "/permission/add"
        if (valid) {
            if (detailMenuCheckedType != null) {
                var detailMenuType = $f.find("input[name='type']:checked").val();
                console.log(detailMenuType)
                console.log(detailMenuCheckedType)
                if ((detailMenuType === "0" || detailMenuType === "1") && detailMenuCheckedType !== 0) {
                    layer.msg("上级资源只能是目录类型！")
                    return;
                } else if (detailMenuType === "2" && detailMenuCheckedType !== 1) {
                    layer.msg("上级资源只能是菜单类型！")
                    return;
                }
            }
            Core.mask("#saveOrUpdateBtn");
            Core.postAjax(url, $f.serialize(), function (data) {
                Core.unmask("#saveOrUpdateBtn");
                if (data.status === 200) {
                    $("#formModal").modal("hide");
                    treeTableConf.table.refresh();
                }
                layer.msg(data.msg);
            }, function () {
                Core.unmask("#saveOrUpdateBtn");
            })
        }
        $f.addClass("was-validated")
    }

    /*编辑*/
    function editRow(permissionId) {
        Core.load("#formContent", "/permission/edit?permissionId=" + permissionId, function () {
            $('#formTitle').text('编辑')
            $("#formModal").modal('show');
        });
    }

    /*删除*/
    function deleteRow(permissionId) {
        Core.confirm("确定删除该分类？", function () {
            Core.postAjax("/permission/delete", {"permissionId": permissionId}, function (data) {
                if (data.status === 200) {
                    treeTableConf.table.refresh();
                }
                layer.msg(data.msg);
            })
        })
    }


    function showMenu(flag) {
        var ztree;
        //树-初始化设置
        var treeSetting = {
            data: {
                simpleData: {
                    enable: true,
                    idKey: "id",
                    pIdKey: "parentId"
                }
            }
        };
        Core.postAjax('/permission/list', {flag: "2"}, function (data) {
            var topMenu = {
                name: "顶层菜单",
                id: 0,
                parentId: "",
                type: 0
            }
            data.unshift(topMenu);
            $.each(data, function (i, item) {
                item.open = true;
            })
            ztree = $.fn.zTree.init($("#permissionTree"), treeSetting, data);
            layer.open({
                type: 1,
                offset: '50px',
                skin: 'layui-layer-molv',
                title: "选择菜单",
                area: ['300px', '450px'],
                /* shade: 0,
                 shadeClose: false,*/
                content: jQuery("#permissionLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var node = ztree.getSelectedNodes();
                    if (node.length == 0) {
                        layer.msg("请选择一个菜单！", function () {
                        });
                        return;
                    }
                    if (flag == 1) {
                        menuCheckedType = node[0].type;
                        //选择上级菜单
                        $("#parentId").val(node[0].id);
                        $("#parentMenu").val(node[0].name);
                    } else if (flag == 2) {
                        detailMenuCheckedType = node[0].type;
                        //选择上级菜单
                        $("#detailParentId").val(node[0].id);
                        $("#detailParentMenu").val(node[0].name);
                    }
                    layer.close(index);
                }
            });
        });
    }


</script>